<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>清晰账本 - 统计分析</title>
    <link rel="stylesheet" href="glassmorphism.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="app_data.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }
        
        body {
            background: linear-gradient(45deg, #6a11cb, #2575fc);
            min-height: 100vh;
            padding: 20px;
            color: #fff;
            padding-bottom: 80px;
        }
        
        .app-container {
            max-width: 480px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .time-tabs {
            display: flex;
            margin-bottom: 25px;
            border-radius: 20px;
            overflow: hidden;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .time-tab {
            flex: 1;
            padding: 15px 0;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .time-tab.active {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .month-selector {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 25px;
        }
        
        .arrow-button {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .current-month {
            font-size: 18px;
            font-weight: bold;
        }
        
        .summary-card {
            border-radius: 24px;
            padding: 25px;
            margin-bottom: 25px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .summary-title {
            font-size: 16px;
            margin-bottom: 15px;
            opacity: 0.8;
        }
        
        .summary-numbers {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        
        .summary-item {
            text-align: center;
        }
        
        .summary-label {
            font-size: 12px;
            opacity: 0.7;
            margin-bottom: 5px;
        }
        
        .summary-value {
            font-size: 20px;
            font-weight: bold;
        }
        
        .chart-container {
            position: relative;
            height: 200px;
            margin-bottom: 10px;
        }
        
        .chart-bar-container {
            display: flex;
            justify-content: space-between;
            height: 100%;
            align-items: flex-end;
        }
        
        .chart-bar {
            width: 8%;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 5px 5px 0 0;
            position: relative;
            transition: height 0.5s;
        }
        
        .chart-bar-expense {
            background: linear-gradient(to top, rgba(255, 94, 98, 0.5), rgba(255, 94, 98, 0.8));
        }
        
        .chart-bar-income {
            background: linear-gradient(to top, rgba(38, 222, 129, 0.5), rgba(38, 222, 129, 0.8));
        }
        
        .chart-label {
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            opacity: 0.7;
        }
        
        .chart-grid {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 25px;
            z-index: -1;
        }
        
        .grid-line {
            position: absolute;
            left: 0;
            right: 0;
            height: 1px;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .pie-chart-container {
            height: 200px;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .pie-chart {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background: conic-gradient(
                #FF5E62 0% 25%,
                #26C9FF 25% 40%,
                #26DE81 40% 55%,
                #FFBE26 55% 70%,
                #7D5FFF 70% 85%,
                #FF8A5B 85% 100%
            );
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        
        .pie-center {
            position: absolute;
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        
        .pie-center-label {
            font-size: 10px;
            opacity: 0.7;
        }
        
        .pie-center-value {
            font-size: 14px;
            font-weight: bold;
        }
        
        .legend {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            width: calc(50% - 5px);
        }
        
        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 3px;
            margin-right: 8px;
        }
        
        .category-stats {
            border-radius: 24px;
            padding: 25px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 25px;
        }
        
        .section-title {
            font-size: 18px;
            margin-bottom: 20px;
        }
        
        .category-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .category-item:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
        }
        
        .category-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
        }
        
        .category-details {
            flex: 1;
        }
        
        .category-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .category-percentage {
            font-size: 12px;
            opacity: 0.7;
        }
        
        .category-amount {
            font-weight: bold;
        }
        
        .progress-container {
            height: 5px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            margin-top: 8px;
            overflow: hidden;
        }
        
        .progress-bar {
            height: 100%;
            border-radius: 3px;
        }
        
        .expense {
            color: #ff5e62;
        }
        
        .income {
            color: #26de81;
        }
        
        .color-1 { background-color: #FF5E62; }
        .color-2 { background-color: #26C9FF; }
        .color-3 { background-color: #26DE81; }
        .color-4 { background-color: #FFBE26; }
        .color-5 { background-color: #7D5FFF; }
        .color-6 { background-color: #FF8A5B; }
        
        .savings-tracker {
            border-radius: 24px;
            padding: 25px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 25px;
        }
        
        .savings-details {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        
        .savings-goal-container {
            position: relative;
            height: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        
        .savings-progress {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            background: linear-gradient(to right, #26de81, #26C9FF);
            border-radius: 4px;
            width: 65%;
        }
        
        .savings-labels {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            opacity: 0.7;
        }
        
        .navigation {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            display: flex;
            justify-content: space-around;
            padding: 15px 0;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: rgba(255, 255, 255, 0.7);
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .nav-item.active {
            color: #fff;
        }
        
        .add-button {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(5px);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: -40px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        /* 储蓄统计样式 */
        .savings-statistics {
            border-radius: 24px;
            padding: 25px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 25px;
        }
        
        .chart-title {
            font-size: 16px;
            margin-bottom: 15px;
            opacity: 0.8;
        }
        
        .savings-goal-charts {
            margin-bottom: 30px;
        }
        
        .empty-state-text {
            text-align: center;
            padding: 20px;
            color: rgba(255, 255, 255, 0.5);
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <h1>统计分析</h1>
        </div>
        
        <div class="time-tabs">
            <div class="time-tab" data-period="week">周</div>
            <div class="time-tab active" data-period="month">月</div>
            <div class="time-tab" data-period="year">年</div>
            <div class="time-tab" data-period="custom">自定义</div>
        </div>
        
        <div class="month-selector">
            <div class="arrow-button" id="prevPeriodBtn">
                <i class="material-icons">chevron_left</i>
            </div>
            <div class="current-month" id="currentPeriod">2023年5月</div>
            <div class="arrow-button" id="nextPeriodBtn">
                <i class="material-icons">chevron_right</i>
            </div>
        </div>
        
        <div class="summary-card">
            <div class="summary-title">本月总览</div>
            <div class="summary-numbers">
                <div class="summary-item">
                    <div class="summary-label">总支出</div>
                    <div class="summary-value expense" id="totalExpense">¥0.00</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">总收入</div>
                    <div class="summary-value income" id="totalIncome">¥0.00</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">结余</div>
                    <div class="summary-value" id="balance">¥0.00</div>
                </div>
            </div>
            
            <div class="chart-container">
                <div class="chart-grid">
                    <div class="grid-line" style="bottom: 25%;"></div>
                    <div class="grid-line" style="bottom: 50%;"></div>
                    <div class="grid-line" style="bottom: 75%;"></div>
                </div>
                
                <div class="chart-bar-container">
                    <div class="chart-bar chart-bar-expense" style="height: 30%;">
                        <div class="chart-label">1日</div>
                    </div>
                    <div class="chart-bar chart-bar-expense" style="height: 45%;">
                        <div class="chart-label">5日</div>
                    </div>
                    <div class="chart-bar chart-bar-expense" style="height: 20%;">
                        <div class="chart-label">10日</div>
                    </div>
                    <div class="chart-bar chart-bar-income" style="height: 75%;">
                        <div class="chart-label">15日</div>
                    </div>
                    <div class="chart-bar chart-bar-expense" style="height: 35%;">
                        <div class="chart-label">20日</div>
                    </div>
                    <div class="chart-bar chart-bar-expense" style="height: 25%;">
                        <div class="chart-label">25日</div>
                    </div>
                    <div class="chart-bar chart-bar-expense" style="height: 15%;">
                        <div class="chart-label">30日</div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="category-stats">
            <div class="section-title">支出分类</div>
            
            <div class="pie-chart-container">
                <div class="pie-chart">
                    <div class="pie-center">
                        <div class="pie-center-label">总支出</div>
                        <div class="pie-center-value" id="totalExpensePie">¥0.00</div>
                    </div>
                </div>
            </div>
            
            <div class="legend">
                <div class="legend-item">
                    <div class="legend-color color-1"></div>
                    <div>餐饮</div>
                </div>
                <div class="legend-item">
                    <div class="legend-color color-2"></div>
                    <div>购物</div>
                </div>
                <div class="legend-item">
                    <div class="legend-color color-3"></div>
                    <div>住房</div>
                </div>
                <div class="legend-item">
                    <div class="legend-color color-4"></div>
                    <div>交通</div>
                </div>
                <div class="legend-item">
                    <div class="legend-color color-5"></div>
                    <div>娱乐</div>
                </div>
                <div class="legend-item">
                    <div class="legend-color color-6"></div>
                    <div>其他</div>
                </div>
            </div>
            
            <div class="category-item">
                <div class="category-icon color-1">
                    <i class="material-icons">restaurant</i>
                </div>
                <div class="category-details">
                    <div class="category-name">餐饮</div>
                    <div class="category-percentage">25% 占比最高</div>
                    <div class="progress-container">
                        <div class="progress-bar color-1" style="width: 25%;"></div>
                    </div>
                </div>
                <div class="category-amount expense" id="expense1">¥0.00</div>
            </div>
            
            <div class="category-item">
                <div class="category-icon color-3">
                    <i class="material-icons">home</i>
                </div>
                <div class="category-details">
                    <div class="category-name">住房</div>
                    <div class="category-percentage">15%</div>
                    <div class="progress-container">
                        <div class="progress-bar color-3" style="width: 15%;"></div>
                    </div>
                </div>
                <div class="category-amount expense" id="expense2">¥0.00</div>
            </div>
            
            <div class="category-item">
                <div class="category-icon color-2">
                    <i class="material-icons">shopping_cart</i>
                </div>
                <div class="category-details">
                    <div class="category-name">购物</div>
                    <div class="category-percentage">15%</div>
                    <div class="progress-container">
                        <div class="progress-bar color-2" style="width: 15%;"></div>
                    </div>
                </div>
                <div class="category-amount expense" id="expense3">¥0.00</div>
            </div>
        </div>
        
        <div class="savings-tracker">
            <div class="section-title">储蓄目标</div>
            <div class="savings-details">
                <div>
                    <div class="summary-label">当前储蓄</div>
                    <div class="summary-value" id="currentSavings">¥0.00</div>
                </div>
                <div>
                    <div class="summary-label">目标金额</div>
                    <div class="summary-value" id="savingsGoal">¥0.00</div>
                </div>
            </div>
            
            <div class="savings-goal-container">
                <div class="savings-progress" id="savingsProgress"></div>
            </div>
            <div class="savings-labels">
                <div>进度: <span id="savingsPercentage">0%</span></div>
                <div>还需: <span id="savingsRemaining">¥0.00</span></div>
            </div>
        </div>
        
        <!-- 储蓄统计区域 -->
        <div class="savings-statistics">
            <div class="section-title">储蓄分析</div>
            
            <div class="savings-goal-charts">
                <div class="chart-title">储蓄目标完成度</div>
                <div id="savingsGoalChart" class="chart-container" style="height: 300px;"></div>
            </div>
            
            <div class="savings-trend-chart">
                <div class="chart-title">储蓄趋势</div>
                <div id="savingsTrendChart" class="chart-container" style="height: 300px;"></div>
            </div>
        </div>
    </div>
    
    <div class="navigation">
        <a href="index.html" class="nav-item">
            <i class="material-icons">home</i>
            <span>首页</span>
        </a>
        <a href="transactions.html" class="nav-item">
            <i class="material-icons">receipt_long</i>
            <span>交易</span>
        </a>
        <a href="statistics.html" class="nav-item active">
            <i class="material-icons">pie_chart</i>
            <span>统计</span>
        </a>
        <a href="my_profile.html" class="nav-item">
            <i class="material-icons">person</i>
            <span>我的</span>
        </a>
    </div>
    
    <script src="app_data.js"></script>
    <script src="mock_data.js"></script>
    <script src="savings_statistics.js"></script>
    <script>
        // 全局变量
        let currentDate = new Date();
        let currentPeriod = 'month'; // 可选值: week, month, year, custom
        let barChart = null;
        let pieChart = null;
        
        // 图表颜色
        const chartColors = [
            'rgba(38, 222, 129, 0.7)',
            'rgba(255, 94, 98, 0.7)',
            'rgba(255, 159, 67, 0.7)',
            'rgba(75, 123, 236, 0.7)',
            'rgba(165, 94, 234, 0.7)',
            'rgba(23, 192, 235, 0.7)',
            'rgba(255, 218, 121, 0.7)'
        ];
        
        // DOM元素
        const currentPeriodElement = document.getElementById('currentPeriod');
        const prevPeriodBtn = document.getElementById('prevPeriodBtn');
        const nextPeriodBtn = document.getElementById('nextPeriodBtn');
        const totalExpenseElement = document.getElementById('totalExpense');
        const totalIncomeElement = document.getElementById('totalIncome');
        const balanceElement = document.getElementById('balance');
        const timeTabs = document.querySelectorAll('.time-tab');
        const pieLegendContainer = document.getElementById('pieLegend');
        const currentSavingsElement = document.getElementById('currentSavings');
        const savingsProgressElement = document.getElementById('savingsProgress');
        const savingsPercentageElement = document.getElementById('savingsPercentage');
        const savingsRemainingElement = document.getElementById('savingsRemaining');
        const savingsGoalElement = document.getElementById('savingsGoal');
        
        // 初始化应用
        function initializeApp() {
            // 设置当前周期显示
            updatePeriodDisplay();
            
            // 加载统计数据
            loadStatistics();
            
            // 添加事件监听
            addEventListeners();
            
            // 更新存款跟踪
            updateSavingsTracker();
        }
        
        // 添加事件监听
        function addEventListeners() {
            // 周期切换事件
            prevPeriodBtn.addEventListener('click', navigateToPreviousPeriod);
            nextPeriodBtn.addEventListener('click', navigateToNextPeriod);
            
            // 时间标签切换事件
            timeTabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    currentPeriod = this.dataset.period;
                    
                    // 更新UI
                    timeTabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新周期显示
                    updatePeriodDisplay();
                    
                    // 重新加载统计数据
                    loadStatistics();
                });
            });
        }
        
        // 加载统计数据
        function loadStatistics() {
            const transactionManager = new window.AppData.TransactionManager();
            let transactions = transactionManager.getTransactions();
            
            // 按周期过滤交易
            const filteredTransactions = filterTransactionsByPeriod(transactions, currentDate, currentPeriod);
            
            // 计算汇总数据
            const summary = calculateSummary(filteredTransactions);
            
            // 更新UI
            updateSummaryUI(summary);
            
            // 渲染图表
            renderBarChart(filteredTransactions);
            renderPieChart(filteredTransactions);
        }
        
        // 按周期过滤交易
        function filterTransactionsByPeriod(transactions, date, period) {
            const year = date.getFullYear();
            const month = date.getMonth();
            const startOfWeek = new Date(date);
            startOfWeek.setDate(date.getDate() - date.getDay()); // 设置为周日
            
            return transactions.filter(transaction => {
                const transactionDate = new Date(transaction.date);
                
                if (period === 'week') {
                    // 获取周的开始和结束
                    const endOfWeek = new Date(startOfWeek);
                    endOfWeek.setDate(startOfWeek.getDate() + 6); // 设置为周六
                    
                    return transactionDate >= startOfWeek && transactionDate <= endOfWeek;
                } else if (period === 'month') {
                    return transactionDate.getFullYear() === year && transactionDate.getMonth() === month;
                } else if (period === 'year') {
                    return transactionDate.getFullYear() === year;
                } else {
                    // 自定义周期暂不处理
                    return transactionDate.getFullYear() === year && transactionDate.getMonth() === month;
                }
            });
        }
        
        // 计算汇总数据
        function calculateSummary(transactions) {
            let totalExpense = 0;
            let totalIncome = 0;
            
            transactions.forEach(transaction => {
                if (transaction.type === 'expense') {
                    totalExpense += transaction.amount;
                } else {
                    totalIncome += transaction.amount;
                }
            });
            
            const balance = totalIncome - totalExpense;
            
            return {
                totalExpense,
                totalIncome,
                balance
            };
        }
        
        // 更新汇总UI
        function updateSummaryUI(summary) {
            totalExpenseElement.textContent = `¥${summary.totalExpense.toFixed(2)}`;
            totalIncomeElement.textContent = `¥${summary.totalIncome.toFixed(2)}`;
            balanceElement.textContent = `¥${summary.balance.toFixed(2)}`;
            
            // 设置结余的颜色
            if (summary.balance >= 0) {
                balanceElement.style.color = '#26de81';
            } else {
                balanceElement.style.color = '#ff5e62';
            }
        }
        
        // 渲染柱状图
        function renderBarChart(transactions) {
            // 按日期分组的数据
            const groupedData = groupTransactionsByDate(transactions);
            const dates = Object.keys(groupedData).sort();
            
            // 准备图表数据
            const expenseData = [];
            const incomeData = [];
            const labels = [];
            
            // 选择合适的日期格式
            let dateFormat = 'MM-dd';
            if (currentPeriod === 'year') {
                dateFormat = 'MM月';
            }
            
            dates.forEach(date => {
                const transactionsForDate = groupedData[date];
                const dateObj = new Date(date);
                
                // 格式化日期
                let label = '';
                if (currentPeriod === 'week' || currentPeriod === 'month') {
                    label = dateObj.getDate().toString();
                } else if (currentPeriod === 'year') {
                    label = (dateObj.getMonth() + 1).toString() + '月';
                }
                
                labels.push(label);
                
                // 计算当天的支出和收入
                let dailyExpense = 0;
                let dailyIncome = 0;
                
                transactionsForDate.forEach(transaction => {
                    if (transaction.type === 'expense') {
                        dailyExpense += transaction.amount;
                    } else {
                        dailyIncome += transaction.amount;
                    }
                });
                
                expenseData.push(dailyExpense);
                incomeData.push(dailyIncome);
            });
            
            // 如果已有图表，销毁它
            if (barChart) {
                barChart.destroy();
            }
            
            // 创建图表
            const ctx = document.getElementById('barChart').getContext('2d');
            barChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '支出',
                            data: expenseData,
                            backgroundColor: 'rgba(255, 94, 98, 0.7)',
                            borderColor: 'rgba(255, 94, 98, 1)',
                            borderWidth: 1
                        },
                        {
                            label: '收入',
                            data: incomeData,
                            backgroundColor: 'rgba(38, 222, 129, 0.7)',
                            borderColor: 'rgba(38, 222, 129, 1)',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(255, 255, 255, 0.1)'
                            },
                            ticks: {
                                color: 'rgba(255, 255, 255, 0.7)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: 'rgba(255, 255, 255, 0.7)'
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: {
                                color: 'rgba(255, 255, 255, 0.7)'
                            }
                        }
                    }
                }
            });
        }
        
        // 渲染饼图
        function renderPieChart(transactions) {
            // 只考虑支出交易
            const expenseTransactions = transactions.filter(t => t.type === 'expense');
            
            // 按分类分组
            const categoryAmount = {};
            expenseTransactions.forEach(transaction => {
                const categoryId = transaction.categoryId;
                
                if (!categoryAmount[categoryId]) {
                    categoryAmount[categoryId] = 0;
                }
                
                categoryAmount[categoryId] += transaction.amount;
            });
            
            // 准备图表数据
            const data = [];
            const labels = [];
            const backgroundColors = [];
            const categoryDetails = [];
            
            Object.keys(categoryAmount).forEach((categoryId, index) => {
                const category = getCategoryById(categoryId, 'expense');
                const amount = categoryAmount[categoryId];
                
                if (category) {
                    data.push(amount);
                    labels.push(category.name);
                    backgroundColors.push(chartColors[index % chartColors.length]);
                    
                    categoryDetails.push({
                        id: categoryId,
                        name: category.name,
                        amount: amount,
                        color: chartColors[index % chartColors.length]
                    });
                }
            });
            
            // 如果已有图表，销毁它
            if (pieChart) {
                pieChart.destroy();
            }
            
            // 创建图表
            const ctx = document.getElementById('pieChart').getContext('2d');
            pieChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: backgroundColors,
                        borderColor: 'rgba(255, 255, 255, 0.1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
            
            // 渲染图例
            renderPieLegend(categoryDetails);
        }
        
        // 渲染饼图图例
        function renderPieLegend(categories) {
            // 按金额排序
            categories.sort((a, b) => b.amount - a.amount);
            
            // 计算总金额
            const totalAmount = categories.reduce((sum, category) => sum + category.amount, 0);
            
            // 生成HTML
            let html = '';
            
            categories.forEach(category => {
                const percentage = totalAmount > 0 ? (category.amount / totalAmount * 100).toFixed(1) : 0;
                
                html += `
                    <div class="legend-item">
                        <div class="legend-color" style="background-color: ${category.color}"></div>
                        <div class="legend-text">${category.name}</div>
                        <div class="legend-value">${percentage}%</div>
                    </div>
                `;
            });
            
            // 更新UI
            pieLegendContainer.innerHTML = html;
        }
        
        // 按日期分组交易
        function groupTransactionsByDate(transactions) {
            const grouped = {};
            
            transactions.forEach(transaction => {
                let date;
                const transactionDate = new Date(transaction.date);
                
                if (currentPeriod === 'year') {
                    // 按月分组
                    date = new Date(transactionDate.getFullYear(), transactionDate.getMonth(), 1).toISOString().split('T')[0];
                } else {
                    // 按日分组
                    date = transaction.date.split('T')[0];
                }
                
                if (!grouped[date]) {
                    grouped[date] = [];
                }
                
                grouped[date].push(transaction);
            });
            
            return grouped;
        }
        
        // 获取分类信息
        function getCategoryById(categoryId, type) {
            const categories = type === 'expense' ? window.AppData.expenseCategories : window.AppData.incomeCategories;
            return categories.find(category => category.id === categoryId);
        }
        
        // 切换上一个周期
        function navigateToPreviousPeriod() {
            if (currentPeriod === 'week') {
                currentDate.setDate(currentDate.getDate() - 7);
            } else if (currentPeriod === 'month') {
                currentDate.setMonth(currentDate.getMonth() - 1);
            } else if (currentPeriod === 'year') {
                currentDate.setFullYear(currentDate.getFullYear() - 1);
            }
            
            updatePeriodDisplay();
            loadStatistics();
        }
        
        // 切换下一个周期
        function navigateToNextPeriod() {
            if (currentPeriod === 'week') {
                currentDate.setDate(currentDate.getDate() + 7);
            } else if (currentPeriod === 'month') {
                currentDate.setMonth(currentDate.getMonth() + 1);
            } else if (currentPeriod === 'year') {
                currentDate.setFullYear(currentDate.getFullYear() + 1);
            }
            
            updatePeriodDisplay();
            loadStatistics();
        }
        
        // 更新周期显示
        function updatePeriodDisplay() {
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth() + 1;
            
            if (currentPeriod === 'week') {
                // 获取周的开始和结束
                const startOfWeek = new Date(currentDate);
                startOfWeek.setDate(currentDate.getDate() - currentDate.getDay());
                
                const endOfWeek = new Date(startOfWeek);
                endOfWeek.setDate(startOfWeek.getDate() + 6);
                
                const startMonth = startOfWeek.getMonth() + 1;
                const endMonth = endOfWeek.getMonth() + 1;
                
                if (startMonth === endMonth) {
                    currentPeriodElement.textContent = `${year}年${startMonth}月${startOfWeek.getDate()}日-${endOfWeek.getDate()}日`;
                } else {
                    currentPeriodElement.textContent = `${year}年${startMonth}月${startOfWeek.getDate()}日-${endMonth}月${endOfWeek.getDate()}日`;
                }
            } else if (currentPeriod === 'month') {
                currentPeriodElement.textContent = `${year}年${month}月`;
            } else if (currentPeriod === 'year') {
                currentPeriodElement.textContent = `${year}年`;
            } else {
                currentPeriodElement.textContent = `自定义周期`;
            }
        }
        
        // 更新存款跟踪
        function updateSavingsTracker() {
            const transactionManager = new window.AppData.TransactionManager();
            const savingsManager = new window.AppData.SavingsManager();
            const transactions = transactionManager.getTransactions();
            const savingsGoals = savingsManager.getSavingsGoals();
            
            // 计算总结余
            let totalBalance = 0;
            transactions.forEach(transaction => {
                if (transaction.type === 'income') {
                    totalBalance += transaction.amount;
                } else {
                    totalBalance -= transaction.amount;
                }
            });
            
            // 确保不是负数
            totalBalance = Math.max(0, totalBalance);
            
            // 获取目标总金额（所有储蓄目标的总和）
            let totalGoalAmount = 0;
            if (savingsGoals && savingsGoals.length > 0) {
                totalGoalAmount = savingsGoals.reduce((sum, goal) => sum + goal.targetAmount, 0);
            } else {
                // 如果没有设置目标，则显示默认提示
                totalGoalAmount = 10000; // 默认目标
            }
            
            // 计算存款百分比
            const percentage = totalGoalAmount > 0 ? Math.min(100, (totalBalance / totalGoalAmount) * 100) : 0;
            const remaining = Math.max(0, totalGoalAmount - totalBalance);
            
            // 更新UI
            currentSavingsElement.textContent = `¥${totalBalance.toFixed(2)}`;
            savingsGoalElement.textContent = `¥${totalGoalAmount.toFixed(2)}`;
            savingsProgressElement.style.width = `${percentage}%`;
            savingsPercentageElement.textContent = `${percentage.toFixed(0)}%`;
            savingsRemainingElement.textContent = `¥${remaining.toFixed(2)}`;
        }
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化模拟数据
            if (window.MockData) {
                window.MockData.initializeMockData();
            }
            
            initializeApp();
            
            // 初始化储蓄统计
            if (window.SavingsStatistics) {
                window.SavingsStatistics.initializeSavingsStatistics();
            }
        });
    </script>
</body>
</html> 